<template>
  <div class="charts-search-block business-select-box">
    <div class="charts-search-block-content">
      <div class="charts-search-select">
        <span>{{$t('report.serviceTypeSelect.assist')}}：</span>
        <el-select
          v-model="formData.assist"
          style="width:150px">
          <el-option v-for="item in assistTypeList" :key="item.value" :label="item.text" :value="item.value"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.workTime')}}：</span>
        <el-select :clearable="false" v-model="formData.dataType" :placeholder="$t('common.base.pleaseSelect')" class="business-dateType-picker">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="dataPickerType === 'monthrange'"
          class="business-date-picker business-select-mr"
          v-model="formData.monthTime"
          type="monthrange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          :clearable="false">
        </el-date-picker>
        <el-date-picker
          v-if="dataPickerType === 'daterange'"
          class="business-date-picker"
          v-model="formData.dateTime"
          type="daterange"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          align="right">
        </el-date-picker>
      </div>
      <div class="charts-search-select">
        <span>OEM：</span>
        <el-select 
          :placeholder="$t('common.base.pleaseSelect')"
          v-model="OEM" 
          filterable
          @change="chooseOEM"
          :clearable="true"
          style="width:150px">
          <el-option v-for="item in oemList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.base.systemKeyword.customer')}}：</span>
        <biz-search-customer-select style="width:180px" :multiple="true" :value="customerIdList" @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true" :placeholder="$t('report.common.allCustomer')"
        />
      </div>
      <div class="charts-search-select usual-biz-team-select">
        <span>{{$t('common.base.department')}}：</span>
        <!-- <el-select v-model="formData.tagIds" multiple :placeholder="$t('common.base.pleaseSelect')" collapse-tags filterable style="width:180px;">
          <el-option
            v-for="item in tagList"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select> -->
        <biz-team-select
          :value="formData.tagIds"
          collapse
          multiple
          style="width:180px;"
          @input="chooseTags"
          :fetch-func="getTagList"
        />
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.fields.taskType.displayName')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.workOrderTypes" 
          :clearable="true"
          @change="changeWorkOrderTypes"
          filterable
          style="width:150px">
          <el-option v-for="(item,index) in workOrderList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('frameHeader.tabMap.costClassification')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          multiple
          collapse-tags
          filterable
          v-model="formData.expensesTypes" 
          style="width:180px"
          :clearable="true">
          <el-option v-for="(item,index) in expensesList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </div>
      <div class="charts-search-select">
        <span>{{$t('common.form.preview.serviceItem.label3')}}：</span>
        <el-select 
          :placeholder="$t('common.base.all')" 
          v-model="formData.workTypes"
          multiple
          collapse-tags
          filterable
          :clearable="true"
          style="width:180px">
          <el-option v-for="item in workTypeList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </div>

    </div>
    <div class="charts-search-block-operator">
      <el-button type='primary' @click="handlerSearchClick">
        {{ $t('common.base.search') }}
      </el-button>
    </div>
  </div>
</template>
<script>

import { lastDayOfMonth, firstDayOfMonth, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { t } from '@src/locales';
import http from 'src/util/HttpUtil';    
import { getCustomerList } from '@src/api/CustomerApi'

import { 
  getAllSelectDataList,
  getTaskTypes, 
  getWorkOrderList,
} from 'src/api/ssbReports';
import { getTagList } from '@src/api/SettingApi.ts';
 
export default {
  name: 'service-type-select',
  data() {
    return {
      formData:{
        assist: 1,
        dateTime: [], // 日时间
        monthTime: [], // 月时间
        workTypes: [], // 工时类别
        workOrderTypes:'', // 工单类型
        dataType: 'month', // 日月维度
        tagIds: [],
        expensesTypes: []
      },
      OEM:'',
      customerIdList:[],
      dataTypeList: [
        {
          label:t('common.base.month'),
          value:'month'
        },
        {
          label:t('common.base.day'),
          value:'day'
        },
      ],
      oemList: [], // OEM列表
      tagList: [], 
      userList: [], // 客户列表列表
      workOrderList:[], // 工时类别列表
      workTypeList:[], // 工单类型列表
      expensesList: [], // 费用归类列表
      assistTypeList:[
        {
          value: 1,
          text: t('report.serviceTypeSelect.includeAssist')
        },
        {
          value: 0,
          text: t('report.serviceTypeSelect.excludeAssist')
        },
      ], // 外协类型
      OEMFieldName:'',
    }
  },
  computed:{
    dataPickerType(){
      return this.formData.dataType === 'month' ? 'monthrange' : 'daterange'
    }
  },
  created() {
    this.formData.dateTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.formData.monthTime = [+firstDayOfMonth(nearDateBy(5, 'month')), +dayTimeEnd()]
    this.getRequestParam()
  },
  methods: {
    changeWorkOrderTypes(){
      this.formData.workTypes = []
      this.getTaskTypes()
    },
    getOemList(){
      http.get('/api/ssbreport/outside/staff/calendar/getCustomerOEMDatabase').then(res=>{
        if(res.code == 0){
          this.oemList = res.data.database
          this.OEMFieldName = res.data.fieldName
        }
      })
    },
    async getTagList (params) {
      // return getWorkHoursTagTree().then(res => {
      //   if (res.code == 0) {
      //     this.tagList = res.data || [];
      //   }
      // })
      try {
        return await getTagList(params);
      } catch (error) {
        console.error("get tag list error", error);
      }
    },
    chooseTags(value){
      this.formData.tagIds = value;
    },
    fetchCustomer(params){
      if (this.OEM) {
        params['conditions'] = [{property:this.OEMFieldName, value:this.OEM, key:null, operator:'eq'}]
      } else {
        params['conditions'] = []
      }
      return getCustomerList({...params})
    },
    chooseCustomer(value){
      this.customerIdList = value
    },
    chooseOEM(){
      this.customerIdList = []
    },
    getTaskTypes(){
      let params = {
        createDateStart:this.formData.dataType == 'month' ? this.formData.monthTime[0] : this.formData.dateTime[0],
        createDateEnd:this.formData.dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        workOrderTypes:this.formData.workOrderTypes ? this.formData.workOrderTypes.split() : [],
        timeDimension:this.formData.dataType,
      }
      getTaskTypes(params).then(res=>{
        if(res.code === 0){
          // this.workTypeList = res.data
        }
      })
    },
    getReasons(){
      getWorkOrderList().then(res=>{
        if(res.code === 0){
          this.workOrderList = res.data
        }
      })
    },
    handlerSearchClick(){
      this.getData()
    },

    /**
     * @des 初始化搜索所需数据
     */
    getRequestParam () {
      this.getOemList()
      this.getReasons()
      // this.getTaskTypes()
      getAllSelectDataList().then(res => {
        if (res.code == 0) {
          const { expenseClassifications, serviceTypes } = res.data;
          this.expensesList = expenseClassifications;
          this.workTypeList = serviceTypes;
        }
      })
      this.getData();
    },
    /**
     * @des 统一封装获取搜索参数
     */
    getSearchParams(){
      const { OEM, customerIdList } = this;
      const { dataType, monthTime, dateTime, workTypes, workOrderTypes, assist, expensesTypes, tagIds } = this.formData;
      let ids = [];
      tagIds.forEach(item=>{
        ids.push(item.id)
      })
      let params = {
        createDateStart:dataType == 'month' ? monthTime[0] : dateTime[0],
        createDateEnd:dataType == 'month' ? +lastDayOfMonth(this.formData.monthTime[1]) : this.formData.dateTime[1],
        serviceTypes:workTypes,
        oem:OEM ? OEM : '',
        workOrderTypes:workOrderTypes ? workOrderTypes.split() : [],
        timeDimension:dataType,
        assist,
        customerIds:customerIdList.map(item=>{
          return item.id
        }),
        expenseClassifications:expensesTypes,
        tagIds:ids
      }
      return params;
    },
    getData(){
      const params = this.getSearchParams()
      this.$emit('change-loading', {type:1, state:true})
      http.post('/api/ssbreport/outside/serviceType/serviceTypeReportData', params).then(res=>{
        if(res.code == 0){
          this.$emit('updateData', {data:res.data})
        }else{
          this.$message.error(res.message)
        }
      }).finally(()=>{
        
        this.$emit('change-loading', {type:1, state:false})
      })
    },
    export(){
      this.$emit('change-loading', {type:2, state:true})
      const params = this.getSearchParams();
      params.isExport = true;
      http.post('/api/ssbreport/outside/serviceType/serviceTypeReportExport', params, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.serviceTypeSelect.reportName');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      }).finally(() =>{
        this.$emit('change-loading', {type:2, state:false})

      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../business.scss';
</style>
<style lang="scss">
@import './usualSelcet.scss'
</style>